import { useState, useEffect, useContext } from 'react';
import { NavBar, Image, List, InfiniteScroll, Toast } from "antd-mobile";
import { CopyOutlined } from '@ant-design/icons';
import { useHistory, useRouteMatch } from 'react-router-dom';
import moment from 'moment';
import copy from 'copy-text-to-clipboard';

import AvatarImage from '../../../components/AvatarImage';
import { MySdkStoreContext } from '../../../context';

import './style.scss';

export default function() {
  const history = useHistory();
  const mySdkStore = useContext(MySdkStoreContext);
  const [result, setResult] = useState([]);
  const { params: { cid } } = useRouteMatch();
  const [pagination, setPagination] = useState({ pageIndex: 1 });

  // 处理”搜索“事件
  const handleSearch = async (pageIndex = 1) => {
    const { rows, current, totalItemCount, totalPage } = await mySdkStore.sdk.searchMessage({ resourceType: 'url', pageIndex, sessionIds: [cid] });
    setResult(pageIndex === 1 ? rows : [...result, ...rows]);
    setPagination({ pageIndex: current, totalItemCount, totalPage })
  }

  // 处理分页获取数据
  const getNextData = async () => {
    await handleSearch(pagination.pageIndex + 1);
  }

  useEffect(() => {
    handleSearch(1);
  }, []);

  // 处理”复制“图标事件
  const handleCopy = (link) => {
    copy(link);
    Toast.show('复制成功');
  }

  return (
    <div className="searchMessageLinkPage">
      <NavBar onBack={() => history.goBack()} style={{ background: '#fff', border: 'none' }}>链接</NavBar>
      <List>
        {result.map(item => {
          return <List.Item
              key={item.msgId}
              prefix={<AvatarImage src={item.from.avatarUrl}
              nickName={item.from?.nickName}
              userName={item.from?.userName}
              userId={item.from?.userId}
              style={{ borderRadius: 8 }} fit='cover' width={40} height={40} />}
              extra={ moment(item.timestamp).format('HH:mm') }
            >
            <div className="linkBox">
              <a href={item.msgContent?.href} target="_blank">{item.msgContent?.title}</a>
              <CopyOutlined onClick={() => handleCopy(item.msgContent?.href || '')} style={{ marginLeft: 12 }} />
            </div>
          </List.Item>
        })}
      </List>
      <InfiniteScroll loadMore={getNextData} hasMore={pagination.pageIndex < pagination.totalPage} />
    </div>)
}